package com.maoshi.shop.platform.task;

import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.bean.entpay.EntPayQueryResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.EntPayService;
import com.maoshi.shop.bean.model.EnterprisePay;
import com.maoshi.shop.service.EnterprisePayService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;


@Slf4j
@Component("enterprisePay")
@AllArgsConstructor
public class EnterprisePayTask {

    private final EntPayService entPayService;

    private final EnterprisePayService enterprisePayService;

    /**
     * 企业支付
     */
    public void sendEnterprisePay() {
        log.info("开始执行发送企业付款任务》》》》》》》》》》》》》》》》》》》》》");

        List<EnterprisePay> enterprisePayList = enterprisePayService.listApplyEnterprisePay();
        enterprisePayService.sendEnterprisePay(enterprisePayList);

        log.info("结束执行发送企业付款任务》》》》》》》》》》》》》》》》》》》》》");
    }

    /**
     * 查询支付情况
     */
    public void queryAndUpdateEntPay() {
        log.info("开始查询企业付款任务》》》》》》》》》》》》》》》》》》》》》》》");

        List<EnterprisePay> enterprisePayList = enterprisePayService.listApplyEnterprisePay();
        if (CollectionUtils.isNotEmpty(enterprisePayList)) {
            for (EnterprisePay enterprisePay : enterprisePayList) {
                try {
                    EntPayQueryResult entPayQueryResult = entPayService.queryEntPay(String.valueOf(enterprisePay.getEntPayOrderNo()));
                    // PROCESSING：处理中
                    if (StrUtil.equalsIgnoreCase(entPayQueryResult.getStatus(), "PROCESSING")) {
                    }
                    // SUCCESS: 转账成功
                    if (StrUtil.equalsIgnoreCase(entPayQueryResult.getStatus(), "SUCCESS")) {
                        enterprisePayService.paySuccess(enterprisePay);
                    }
                    // FAILED: 转账失败
                    if (StrUtil.equalsIgnoreCase(entPayQueryResult.getStatus(), "FAILED")) {
                        enterprisePayService.payFailed(enterprisePay);
                        log.error(entPayQueryResult.getReason());
                    }

                } catch (WxPayException e) {
                    e.printStackTrace();
                }
            }
        }
        log.info("结束查询企业付款任务》》》》》》》》》》》》》》》》》》》》》》》");
    }

}
